//
//  FlowControlViewController+Request.m
//  NaRiLSVMT
//
//  Created by jmsre on 14-8-25.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//

#import "FlowControlViewController+Request.h"
#import "MBProgressController.h"
#import "Network_Operation.h"
#import "FlowDetailViewController.h"
//#import "TopLargerScrInFlow.h"
#import "TopLargerScreenView.h"
//#import "AllNodesInScrollView.h"


//extern  BOOL    isNodePagePlay;//是否是在节点界面播放。是：YES.否：NO.

extern  NSInteger   lastFlowNumber;//前一个处理的流程No.或者当前

extern  UIImageView *topImageViewInFlow;//流程控制主页面，背景图片

extern  NSString    *intervalPlayTime;//播放间隔时间

//extern  BOOL    currentFlowIsPlaying;//是否是当前流程在播放

@implementation FlowControlViewController (Request)


-(void)NRLSMTGetFlowNodeForPad
{
    [[MBProgressController sharedInstance] showWithText:@"正在努力加载..."];
    WeakSelf;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *getFlowNodeStr = [Network_API Network_API_GetFlowNodeForPad];
        
        AFHTTPClient *httpClient = [Network_Operation httpClientWithUrl:getFlowNodeStr];
        NSString    *str = [NSString stringWithFormat:@"[{\"classname\":%@,\"methodname\":%@,\"parameterClasss\":[{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@}]}]",@"\"iControlSolutionService\"",@"\"getFlowNodeForPad\"",@"\"flowId\"",wself.flowId,@"\"java.lang.String\""];
        [httpClient postPath:getFlowNodeStr
                  parameters:@{@"jsonstr":str,
                               @"callback":@""
                               }
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         if([responseObject isKindOfClass:[NSString class]])
                         {
                             NSString *resStr = [NSString stringWithString:responseObject];
                             if(!([resStr rangeOfString:@"id"].location == NSNotFound))
                             {
                                 NSLog(@"getFlowNodeForPad Success");
                                 currentQueryingflowId = wself.flowId;//本流程Id
                                 allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"receiveFlowNodeData"] = [NSMutableArray arrayWithArray:[Common jsontoArr:resStr]];
                                 wself.flowNodeId = [[allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"receiveFlowNodeData"] objectAtIndex:0] objectForKey:@"id"];
                                 
                                 
                                 if ([wself.flowNoteIntervalTime.text intValue] < 5)
                                 {
                                     [[MBProgressController sharedInstance] showTipsOnlyText:@"播放间隔时间不能小于5" AndDelay:1.5];
                                     wself.flowNoteIntervalTime.text = @"5";
                                 }
                                 
                               //   [wself.flowNoteIntervalTime endEditing:NO];
                                 
                                 if(wself.buttonIdInFlowBottom%3 == 0)
                                 {
                                     dispatch_async(dispatch_get_main_queue(), ^{
                                         [wself NRLSMTGetThumbnailByFlowNodeId];//获取本流程节点详细信息
                                     });
                                 }
                                 else if(wself.buttonIdInFlowBottom%3 == 1 || wself.buttonIdInFlowBottom%3 == 2)
                                 {
                                     allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"playFlag"] = @(1);
                                     isPlayingFlowId = currentQueryingflowId;
                                     isPlayingFlowNumber = lastFlowNumber;
                                     //获取所有节点信息
                                     dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                         [allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"receiveFlowNodeData"] enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop){
                                             __block NSDictionary *dic = (NSDictionary *)obj;
                                             __block NSString    *nodeId = [dic objectForKey:@"id"];
                                             dispatch_async(dispatch_get_main_queue(), ^{
                                                 [wself NRLSMTGetThumbnailByFlowNodeIdForPlay:nodeId];
                                             });
                                         }];
                                     });
                                     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                                       //  sleep(1);
                                         if(topImageViewInFlow != nil){
                                         [topImageViewInFlow removeFromSuperview];
                                         }
                                         
                                         TopLargerScreenView *topLargerScr = allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"topLargerScr"];
                                         AllNodesInScrollView *bottomSmaPic = allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"bottomSmaPic"];
                                         bottomSmaPic.delagateFlowForTapOrPlay = wself;
                                         
                                         
                                         NSMutableArray  *TmpViewNameArray = [NSMutableArray array];
                                         for(NSDictionary *dic in allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"receiveFlowNodeData"])
                                         {
                                             [TmpViewNameArray addObject:[dic objectForKey:@"name"]];
                                         }
                                         
                                         
                                         topLargerScr.viewNameArray = [NSArray arrayWithArray:TmpViewNameArray];
                                         bottomSmaPic.nameArray = [NSArray arrayWithArray:TmpViewNameArray];
                                         
                                         [self.topViewInFlow addSubview:topLargerScr];
                                         
                                         [bottomSmaPic initWithNameButtons];
                                         [topLargerScr initWithViews];
                                         
                                        // wself.flowNoteIntervalTime.enabled = NO;
                                         
                                         /****************将本流程数据保存用于播放*****************/
                                         /******************更新 allFlowDataArr*****************/
                                         allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"nodeThumbnailArr"] = allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"allNodeDataInFlow"];
                                         allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"intervalTime"] = @(wself.flowNoteIntervalTime.text.integerValue);
                                         /*****************************************************/
                                         
                                         if (wself.buttonIdInFlowBottom%3 == 1)//单次播放
                                         {
                                             allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"pauseFlag"] = @(2);
                                             [bottomSmaPic onceOrcyclesPlay:allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"nodeButtonArr"] StartIndex:StringFromId(allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"havePlayNodeIndex"]).integerValue Interval:StringFromId(allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"intervalTime"]).integerValue IsCyclesPlay:NO isPause:[allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"pauseFlag"] intValue]];
                                         }
                                         else if(wself.buttonIdInFlowBottom%3 == 2)//循环播放
                                         {
                                             allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"pauseFlag"] = @(2);
                                             [bottomSmaPic onceOrcyclesPlay:allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"nodeButtonArr"] StartIndex:StringFromId(allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"havePlayNodeIndex"]).integerValue Interval:StringFromId(allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"intervalTime"]).integerValue IsCyclesPlay:YES isPause:[allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"pauseFlag"] intValue]];
                                         }
                                     });
                                 }
                             }
                             else
                             {
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                    // self.navigationController.navigationBar.hidden = YES;
                                     [[MBProgressController sharedInstance] hide];
                                     [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点失败" AndDelay:1.5];
                                 });
                                 NSLog(@"直接返回");
                             }
                         }
                         else {
                             dispatch_async(dispatch_get_main_queue(), ^{
                               //  self.navigationController.navigationBar.hidden = YES;
                                 [[MBProgressController sharedInstance] hide];
                                 [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点失败"
                                                                                AndDelay:1.5];
                             });
                             NSLog(@"直接返回");
                         }
                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         dispatch_async(dispatch_get_main_queue(), ^{
                          //   self.navigationController.navigationBar.hidden = YES;
                             [[MBProgressController sharedInstance] hide];
                             [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点失败"
                                                                            AndDelay:1.5];
                         });
                     }];
    });
    [[MBProgressController sharedInstance] hide];
}



-(void)NRLSMTGetThumbnailByFlowNodeId
{
    WeakSelf;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *getThumbnailStr = [Network_API Network_API_GetThumbnailByFlowNodeId];
        
        AFHTTPClient *httpClient = [Network_Operation httpClientWithUrl:getThumbnailStr];
        NSString    *str = [NSString stringWithFormat:@"[{\"classname\":%@,\"methodname\":%@,\"parameterClasss\":[{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@},{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@}]}]",@"\"iControlSolutionService\"",@"\"getThumbnailByFlowNodeId\"",@"\"userId\"",subjectId,@"\"java.lang.String\"",@"\"flowNodeId\"",wself.flowNodeId,@"\"java.lang.String\""];
        [httpClient postPath:getThumbnailStr
                  parameters:@{@"jsonstr":str,
                               @"callback":@""
                               }
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         if([responseObject isKindOfClass:[NSString class]])
                         {
                             NSString *resStr = [NSString stringWithString:responseObject];
                             if(!([resStr rangeOfString:@"name"].location == NSNotFound))
                             {
                                 NSLog(@"getThumbnailByFlowNodeId Success");
                                 
                                 NSMutableArray *arr = [NSMutableArray arrayWithArray:[Common jsontoArr:resStr]];
                                 
                                 if(wself.buttonIdInFlowBottom%3 ==0)
                                 {                                     
                                     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                                         
                                         FlowDetailViewController *flowDetailViewController = [[FlowDetailViewController alloc] initWithNibName:@"FlowDetailViewController" bundle:nil];
                                         flowDetailViewController.delegateFlowDetail = wself;
                                         allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"receiveFlowDetailData"] = [NSMutableArray arrayWithArray:allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"receiveFlowNodeData"]];
                                         
                                         allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"firstNodeData"] = [NSMutableArray arrayWithArray:arr];
                                         
                                         flowDetailViewController.flowName = wself.flowName;
                                         intervalPlayTime = wself.flowNoteIntervalTime.text;
                                         
                                         allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"isNodePagePlay"] = @(1);
                                         
                                         if([allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"playFlag"] intValue] == 1)
                                         {
                                             AllNodesInScrollView *bottomSmaPic = allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"bottomSmaPic"];
                                             for (UIView *v in bottomSmaPic.subviews) {
                                                 if ([v isKindOfClass:[UIButton class]]) {
                                                     [v removeFromSuperview];
                                                 }
                                             }
                                             [allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"topLargerScr"] removeFromSuperview];
                                             /****************将本流程数据保存用于播放*****************/
                                             /******************更新 allFlowDataArr*****************/
                                             allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"nodeThumbnailArr"] = allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"allNodeDataInFlow"];
                                             /*****************************************************/
                                         }
                                         PostNoticeObserver(NoticeKey_ScrollViewThird, flowDetailViewController);
                                         
//                                         [self presentViewController:flowDetailViewController animated:NO completion:nil];
                                         
                                     });
                                 }
                             }
                             else
                             {
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                    // self.navigationController.navigationBar.hidden = YES;
                                     [[MBProgressController sharedInstance] hide];
                                     [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点播放缩略图失败" AndDelay:1.5];
                                 });
                                 NSLog(@"直接返回");
                             }
                         }
                         else {
                             dispatch_async(dispatch_get_main_queue(), ^{
                              //   self.navigationController.navigationBar.hidden = YES;
                                 [[MBProgressController sharedInstance] hide];
                                 [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点播放缩略图失败"
                                                                                AndDelay:1.5];
                             });
                             NSLog(@"直接返回");
                         }
                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         dispatch_async(dispatch_get_main_queue(), ^{
                           //  self.navigationController.navigationBar.hidden = YES;
                             [[MBProgressController sharedInstance] hide];
                             [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点播放缩略图失败"
                                                                            AndDelay:1.5];
                         });
                     }];
    });
    [[MBProgressController sharedInstance] hide];
}


-(void)NRLSMTGetThumbnailByFlowNodeIdForPlay:(NSString *)flowNodeId
{
//    [[MBProgressController sharedInstance] showWithText:@"正在努力加载..."];
//    WeakSelf;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *getThumbnailStr = [Network_API Network_API_GetThumbnailByFlowNodeId];
        
        AFHTTPClient *httpClient = [Network_Operation httpClientWithUrl:getThumbnailStr];
        NSString    *str = [NSString stringWithFormat:@"[{\"classname\":%@,\"methodname\":%@,\"parameterClasss\":[{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@},{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@}]}]",@"\"iControlSolutionService\"",@"\"getThumbnailByFlowNodeId\"",@"\"userId\"",subjectId,@"\"java.lang.String\"",@"\"flowNodeId\"",flowNodeId,@"\"java.lang.String\""];
        [httpClient postPath:getThumbnailStr
                  parameters:@{@"jsonstr":str,
                               @"callback":@""
                               }
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         if([responseObject isKindOfClass:[NSString class]])
                         {
                             NSString *resStr = [NSString stringWithString:responseObject];
                             if(!([resStr rangeOfString:@"name"].location == NSNotFound))
                             {
                                 NSLog(@"getThumbnailByFlowNodeId Success");
                                 NSLog(@"%@",flowNodeId);
                                 NSMutableArray *arr = [NSMutableArray arrayWithArray:[Common jsontoArr:resStr]];
                                 
                                [allFlowDataArr[lastFlowNumber][currentQueryingflowId][@"allNodeDataInFlow"] addObject:@{flowNodeId: arr}];
                             }
                             else
                             {
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                  //   self.navigationController.navigationBar.hidden = YES;
                                     [[MBProgressController sharedInstance] hide];
                                     [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点播放缩略图失败" AndDelay:1.5];
                                 });
                                 NSLog(@"直接返回");
                             }
                         }
                         else {
                             dispatch_async(dispatch_get_main_queue(), ^{
                              //   self.navigationController.navigationBar.hidden = YES;
                                 [[MBProgressController sharedInstance] hide];
                                 [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点播放缩略图失败"
                                                                                AndDelay:1.5];
                             });
                             NSLog(@"直接返回");
                         }
                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         dispatch_async(dispatch_get_main_queue(), ^{
                           //  self.navigationController.navigationBar.hidden = YES;
                             [[MBProgressController sharedInstance] hide];
                             [[MBProgressController sharedInstance] showTipsOnlyText:@"查询节点播放缩略图失败"
                                                                            AndDelay:1.5];
                         });
                     }];
    });
    [[MBProgressController sharedInstance] hide];
}


-(void)NRLSMTFlowNodeAutoPlay:(NSString *)flowNodeId isTurn:(NSString *)turn
{
//    [[MBProgressController sharedInstance] showWithText:@"正在努力加载..."];
    WeakSelf;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *flowNodeAutoPlayStr = [Network_API Network_API_FlowNodeAutoPlay];
        
        AFHTTPClient *httpClient = [Network_Operation httpClientWithUrl:flowNodeAutoPlayStr];
        NSString    *str = [NSString stringWithFormat:@"[{\"classname\":%@,\"methodname\":%@,\"parameterClasss\":[{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@},{\"parametername\":%@,\"parametervalue\":\"%@\",\"valuetype\":%@}]}]",@"\"iControlSolutionService\"",@"\"flowNodeAutoPlay\"",@"\"flowNodeId\"",flowNodeId,@"\"java.lang.String\"",@"\"flag\"",turn,@"\"java.lang.String\""];
        [httpClient postPath:flowNodeAutoPlayStr
                  parameters:@{@"jsonstr":str,
                               @"callback":@""
                               }
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         if([responseObject isKindOfClass:[NSString class]])
                         {
                             NSString *resStr = [NSString stringWithString:responseObject];
                             if(!([resStr rangeOfString:@"status"].location == NSNotFound))
                             {
                                 NSLog(@"flowNodeAutoPlay Success");
                                 
                                 
                             }
                             else
                             {
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                 //   self.navigationController.navigationBar.hidden = YES;
                                     [[MBProgressController sharedInstance] hide];
                                     [[MBProgressController sharedInstance] showTipsOnlyText:@"流程节点切屏失败" AndDelay:1.5];
                                 });
                                 NSLog(@"直接返回");
                             }
                             
//                             if(![wself.oldIndex isEqualToString:@""] && wself.oldIndex != nil && [turn isEqualToString:@"true"])
//                             {
//                                 if(![wself.oldIndex isEqualToString:flowNodeId])
//                                 [self NRLSMTFlowNodeAutoPlay:wself.oldIndex isTurn:@"false"];
//                             }
                             if([turn isEqualToString:@"true"])
                             {
                                 // 同一个屏幕
                                 if(!self.nowIndex){
                                     self.nowIndex = flowNodeId;
                                 }
                                 if([self.nowIndex isEqualToString:flowNodeId]){
                                     if(self.oldIndex == nil || [self.oldIndex isEqualToString:@""]){
                                         wself.oldIndex = flowNodeId;
                                     }
                                     else{
                                         if(![self.oldIndex isEqualToString:self.nowIndex])
                                             [self NRLSMTFlowNodeAutoPlay:wself.oldIndex isTurn:@"false"];
                                     }
                                 }
                                 else
                                 {
                                     wself.oldIndex = wself.nowIndex;
                                     if(![wself.oldIndex isEqualToString:@""] && wself.oldIndex != nil){
                                         [self NRLSMTFlowNodeAutoPlay:wself.oldIndex isTurn:@"false"];
                                     }
                                 }
                                 wself.nowIndex = flowNodeId;
                             }

                                // if(![wself.oldIndex isEqualToString:flowNodeId])
//                                   wself.oldIndex = flowNodeId;
//                                else
//                                [self NRLSMTFlowNodeAutoPlay:wself.oldIndex isTurn:@"false"];}
                         }
                         else {
                             dispatch_async(dispatch_get_main_queue(), ^{
                               //  self.navigationController.navigationBar.hidden = YES;
                                 [[MBProgressController sharedInstance] hide];
                                 [[MBProgressController sharedInstance] showTipsOnlyText:@"流程节点切屏失败"
                                                                                AndDelay:1.5];
                             });
                             NSLog(@"直接返回");
                         }
                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         dispatch_async(dispatch_get_main_queue(), ^{
                            // self.navigationController.navigationBar.hidden = YES;
                             [[MBProgressController sharedInstance] hide];
                             [[MBProgressController sharedInstance] showTipsOnlyText:@"流程节点切屏失败"
                                                                            AndDelay:1.5];
                         });
                     }];
    });
    [[MBProgressController sharedInstance] hide];
}




@end
